package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVerifyCode(String phone, String code) {
        ValueOperations<String, String> strOps = template.opsForValue();

        String key = "verify_Code:"+phone;

        strOps.set(key,code, Consts.VERIFY_CODE_VAI_TIME*60L,TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {

        String key = "verify_Code:"+phone;

        return template.opsForValue().get(key);


    }

    @Override
    public String setToken(UserInfo user) {


        // 生成一个token(随机,唯一)
        String str = UUID.randomUUID().toString().replace("-","");

        String key = RedisKeys.TOKEN_CODE.join(str);

        String userJson = JSON.toJSONString(user);

        template.opsForValue().set(key,userJson,RedisKeys.TOKEN_CODE.getTime(),TimeUnit.SECONDS);

        return str;
    }

    @Override
    public UserInfo getUserByToken(String token) {

        if (token == null){
            return null;
        }
        String key = RedisKeys.TOKEN_CODE.join(token);

        String userJson = template.opsForValue().get(key);

        if (userJson == null){
            return null;
        }
        // 重置有效时间
        template.expire(key,RedisKeys.TOKEN_CODE.getTime(),TimeUnit.SECONDS);
        return JSON.parseObject(userJson,UserInfo.class);

    }
}
